package mx.itesm.gda.clever.ui;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.texteditor.ITextEditor;

public class CompileHandler extends AbstractHandler {
	
	@Override
	public Object execute(final ExecutionEvent event) throws ExecutionException {
		final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		if (window == null) { throw new ExecutionException(
				"no active workbench window"); //$NON-NLS-1$
		}
		
		final IWorkbenchPage page = window.getActivePage();
		if (page == null) { throw new ExecutionException("no active workbench page"); //$NON-NLS-1$
		}
		
		// Lexical analysis
		//		
		// try {
		// page.showView(TokensView.ID);
		// } catch (final PartInitException exception) {
		//			throw new ExecutionException("error initializing the Tokens view"); //$NON-NLS-1$
		// }
		//		
		// IWorkbenchPart part = page.getActivePart();
		// IEditorPart editor = page.getActiveEditor();
		// if (part instanceof TokensView && editor instanceof ITextEditor) {
		// try {
		// ((TokensView) part).scan((ITextEditor) editor);
		// } catch (IOException exception) {
		// MessageDialog.openError(HandlerUtil.getActiveShell(event), null,
		// exception.getLocalizedMessage());
		// }
		// }
		
		// Syntactic analysis
		
		try {
			page.showView(SyntaxTreeView.ID);
		} catch (final PartInitException exception) {
			throw new ExecutionException("error initializing the Syntax Tree view"); //$NON-NLS-1$
		}
		
		IWorkbenchPart part = page.getActivePart();
		IEditorPart editor = page.getActiveEditor();
		if (part instanceof SyntaxTreeView && editor instanceof ITextEditor) {
			try {
				((SyntaxTreeView) part).parse((ITextEditor) editor);
			} catch (Exception exception) {
				MessageDialog.openError(HandlerUtil.getActiveShell(event), null,
						exception.getLocalizedMessage());
			}
		}
		
		// Semantic analysis
		
		try {
			page.showView(SymbolTableView.ID);
		} catch (final PartInitException exception) {
			throw new ExecutionException("error initializing the Symbol Table view"); //$NON-NLS-1$
		}
		
		part = page.getActivePart();
		editor = page.getActiveEditor();
		if (part instanceof SymbolTableView && editor instanceof ITextEditor) {
			try {
				((SymbolTableView) part).analyze((ITextEditor) editor);
			} catch (final Exception exception) {
				MessageDialog.openError(HandlerUtil.getActiveShell(event), null,
						exception.getLocalizedMessage());
			}
		}
		
		return null;
	}
	
}
